package com.jjty.dataGenerator.sxhcampus.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

/**
 * @Author: huangyulong
 * @createTime: 2023-11-08 16:17
 * @Description:
 */
public class Coder {


    public static String getConcatStr(Object o){
        JSONObject jsonObject = JSON.parseObject(JSONObject.toJSONString(o));
        Set<String> keySet = jsonObject.keySet();
        List<String> list = new ArrayList<>();
        list.addAll(keySet);
        System.out.println("排序前key的顺序");
        for (String key : list){
            System.out.print(key+",");
        }
        Collections.sort(list);
        StringBuilder stringBuilder = new StringBuilder();
        System.out.println("当前key的顺序");
        for (String key : list){
            if(key.equals("sig"))continue;
            System.out.print(key+",");
            String value = jsonObject.getString(key);
            if((value.startsWith("[") && value.endsWith("]")) || (value.startsWith("{") || value.endsWith("}") ))continue;
            stringBuilder.append(key+"="+jsonObject.getString(key));
        }
        return stringBuilder.toString();
    }


    public static String hmac_sha1(String value, String key) {
        try {
            // Get an hmac_sha1 key from the raw key bytes
            byte[] keyBytes = key.getBytes();
            SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA1");

            // Get an hmac_sha1 Mac instance and initialize with the signing key
            Mac mac = Mac.getInstance("HmacSHA1");
            mac.init(signingKey);

            // Compute the hmac on input data bytes
            byte[] rawHmac = mac.doFinal(value.getBytes());

            // Convert raw bytes to Hex
            String hexBytes = byte2hex(rawHmac);
            return hexBytes;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    private static String byte2hex(final byte[] b){
        String hs="";
        String stmp="";
        for (int n=0; n<b.length; n++){
            stmp=(Integer.toHexString(b[n] & 0xFF));
            if (stmp.length()==1) hs=hs+"0"+stmp;
            else hs=hs+stmp;
        }
        return hs;
    }

}
